package com.gulimall.ssoclient.controller;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {
    @Value("${sso.server.url}")
    String ssoServerUrl;
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    @GetMapping("/employees")
    public String list(Model model ,HttpSession session,@RequestParam(value = "token",required = false) String token){
        if (!StringUtils.isEmpty(token)){
            //获取服务器的用户信息
            RestTemplate restTemplate =new RestTemplate();
            //返回服务器的响应信息
            ResponseEntity<String> entity = restTemplate.getForEntity("http://ssoserver.com:8080/userinfo?token=" + token, String.class);
            String body = entity.getBody();
            session.setAttribute("userLogin",body);
        }
        Object userLogin = session.getAttribute("userLogin");
        if (!StringUtils.isEmpty(userLogin)){
            List<String> employees =new ArrayList<>();
            employees.add("张飞");
            employees.add("关羽");
            model.addAttribute("employees",employees);
            return "list";
        }else {
            return "redirect:"+ssoServerUrl+"?redirect_url=http://client2.com:8082/employees";
        }

    }
}
